<?php 
function AppBuildAdminMenuHook($backend)
{
	$backend->addMenuItem(ADMIN_CONTENT, __('Listings'),'/listings/index/');
	$backend->addMenuItem(ADMIN_CONTENT, __('Listing Types'),'/listing_types/index/');
	$backend->addMenuItem(ADMIN_CONTENT, __('Reviews'),'/reviews/index/');
	$backend->addMenuItem(ADMIN_CONTENT, __('Review Comments'),'/review_comments/index/');
	$backend->addMenuItem(ADMIN_CONTENT, __('Categories'),'/categories/categories/index');
	$backend->addMenuItem(ADMIN_CONTENT, __('Gallery Comments'),'/asset_comments/index/');
	$backend->addMenuItem(ADMIN_CONTENT, __('Static Pages'), '/static_pages/static_pages/index');

	$backend->addMenuItem(ADMIN_SETTINGS, __('General'), '/site_config/setting/General');
	$backend->addMenuItem(ADMIN_SETTINGS, __('Listing'), '/site_config/setting/Listing');
	$backend->addMenuItem(ADMIN_SETTINGS, __('Review'), '/site_config/setting/Review');
	$backend->addMenuItem(ADMIN_SETTINGS, __('Email Settings'), '/cms/email_config/setting');
  	$backend->addMenuItem(ADMIN_SETTINGS, __('Newsletter'), '/newsletters/newsletter_configs/setting');
	if(isInstalled('geo'))
	{
		$backend->addMenuItem(ADMIN_SETTINGS, __('Map'), '/map_config/setting');
		$backend->addMenuItem(ADMIN_SETTINGS, __('Map Icons'), '/map_config/icons');
	}
	if(isInstalled('smf'))
	{
		$backend->addMenuItem(ADMIN_SETTINGS, __('Simple Machine Forum'), '/smf/smf_config/setting');
	}
	if(isInstalled("import"))
	{
		$backend->addMenuItem(ADMIN_MISC, __('Import Csv'), '/listing_import/import');
	}
	if(cr("ListingConfig.business_owner"))
	{
		$backend->addMenuItem(ADMIN_CONTENT, __('Listing Claims'), '/listing_claims');
	}
	$backend->addMenuItem(ADMIN_SETTINGS, __('Bad Words'), '/users/user_content_configs/setting');
	if(isInstalled('sociable'))
	{
		$backend->addMenuItem(ADMIN_SETTINGS, __('Facebook'), '/facebook_config/setting');
		$backend->addMenuItem(ADMIN_SETTINGS, __('Facebook Fields'), '/facebook_config/mapFbFields');
	}
	if(isInstalled('paid_listings'))
	{
		$backend->addMenuItem(ADMIN_SETTINGS, __('Paid Listings'), '/paid_listings/paid_listing_config/setting');
		//$backend->addMenuItem(ADMIN_MISC, __('Plans'), '/paid_listings/plans');
		//$backend->addMenuItem(ADMIN_MISC, __('Orders'), '/paid_listings/orders/dashboard');
		//$backend->addMenuItem(ADMIN_SETTINGS, __('Payment Handlers'), '/paid_listings/payment_handlers/index');
	}	
	$backend->addMenuItem(ADMIN_MISC, __('Field Groups'), '/eav/fieldsets/index');
	$backend->addMenuItem(ADMIN_MISC, __('User Fields'), '/user_fields/index');
	$backend->addMenuItem(ADMIN_MISC, __('Email Templates'), '/email_templates/index');
	$backend->addMenuItem(ADMIN_MISC, __('Scopes'), '/content_scopes/index');
	$backend->addMenuItem(ADMIN_MISC, __('Dynamic Pages'), '/dynamic_pages/index');
	//$backend->addMenuItem(ADMIN_SETTINGS, __('Licenses'), '/config/generic_config/setting/License');
	$backend->addMenuItem(ADMIN_MISC, __('Global Meta Information'), '/meta_information/pages');
}
function AppInitHook($ctrl)
{
	App::import('Vendor','SiteUrl');
	App::import("Vendor","SiteTreeCallbacks");
	App::import("Vendor","AppUtility");
	$ctrl->helpers[]  = "AppHtml";
	$ctrl->helpers[]  = "Form";
	$ctrl->helpers[] = "Cms.BreadCrumb";
}
function AppBeforeFilterHook($ctrl)
{
	//@dynamic page interaction.
	App::import("Vendor","DynamicPageRoutes");
	$DynamicPageModel = cri('DynamicPage');
	//create caching it don't exists
	if(!is_file(DynamicPageRoutes::getRoutesFilepath()))
	{
		$DynamicPage = new DynamicPageRoutes();
		$DynamicPage->savePagesPath($DynamicPageModel); 
	}
	if(isset($ctrl->params['dynamicField']) && isset($ctrl->params['dynamicFieldValue']) && !$ctrl->data)
	{
		$field = $ctrl->params['dynamicField'];
		$value = @$ctrl->params['dynamicFieldValue'];
		$value = $DynamicPageModel->extractOptionValueFromSlug($field,$value);
		if($DynamicPageModel->isPageField($field) && is_null($value) == false)
		{
			$DynamicPageModel->setModelsScopes($field,$value);
			Configure::write('DynamicPage.field',$field);
			Configure::write('DynamicPage.value',$value);
		}
	}
}
/**
 * Sets page title prefix for dynamic pages.
 * @param unknown_type $ctrl
 */
function AppBeforeRenderHook($ctrl)
{
	//@dynamic page interaction.
	if(cr("DynamicPage.field"))
	{
		$dynamicPageInfo = cri("DynamicPage")->getPageInfo(cr("DynamicPage.field"));
		//use title format to be shown on this page.
		$title = $dynamicPageInfo['DynamicPage']['page_title'];
		//show title is admin has %s to 
		$value = $dynamicPageInfo['DynamicPage']['fieldOptions'][cr("DynamicPage.value")];
		$title = String::insert($title,array("title"=>$value));
		$oldTitle =$ctrl->pageTitle;
		$ctrl->pageTitle = $title;
		if($oldTitle)
		{
			$ctrl->pageTitle = $ctrl->pageTitle." :: ".$oldTitle;
		}
	}
	//@todo this a bad practise.Need better a better way.
	include CONFIGS.'js_error_msg.php';
	$ctrl->set('encodedErrorMsgs',$encodedErrorMsgs);
}
function AppAfterComponentInitHook($ctrl)
{
	if(cr('cmsInstalled') && @strpos($_SERVER['REQUEST_URI'],'/cms/startTestSession') === false)
	{
		AppUtility::initializeConfiguration();
	}
}

function AppBeforeShellDispatchHook($ctrl)
{
  //@todo Dirty hack : A temporary check. ConfigInitHooks needs to fixed so that cmsInstalled is can also be used for shell calls.
  if(is_file(CONFIG_FILE) == false || (isset($ctrl->args[0]) && in_array($ctrl->args[0],array("install","clean"))))
  {
    return; 
  }
  App::import('Vendor','SiteUrl');
  App::import("Vendor","SiteTreeCallbacks");
  App::import("Vendor","AppUtility");
  AppUtility::initializeConfiguration();
}
function AppafterVoteHook($controller,$voteData)
{
	if($voteData['score'] == 1)
	{			
		$reviewData = cri('Review')->find('first',array('conditions'=>array('Review.id'=>$voteData['item_id']),'recursive'=>0));
		$authedUser = $controller->Session->read('Auth.User');
		$sendMailOnReviewLiked = $reviewData['User']['onReviewLiked'];
		if($sendMailOnReviewLiked && ($reviewData['User']['id'] != $voteData['user_id']))
		{
			$controller->set('username',$reviewData['Review']['poster']['display_name']);
			$controller->set('listingTitle',$reviewData['Listing']['title']);
			$controller->set('liker',$authedUser['display_name']);
			
			App::import('Vendor', 'EmailOperation');
			EmailOperation::sendMail('mailOnReviewLiked',array($controller,$reviewData));
		}	
	}
					
}

function AppafterCommentPublishHook($controller,$commentId)
{
	if($controller->name == 'ReviewComments')
	{
		$controller->_sendNotificationMail($commentId);
	}	
	if($controller->name == 'AssetComments')
	{		
		$controller->__applyNotification($commentId,null);
	}
}

function AppGetSiteMapPagesHook(SiteMap $SiteMapModel)
{
	//@dynamic page interaction.
		$listingIndexPages = new GigaAction(
			"listingIndex",
			__('Listing Index'),
			array("controller"=>"listings","action"=>"index")
		);
		$advancesSearchPages = new GigaAction(
			"advancedSearch",
			__('Advanced Search'),
			array("controller"=>"listings","action"=>"index",'advancedSearch')
		);
		$registerPage = new GigaAction(
			"user_register",
			__("Register"),
			array("controller"=>"users","action"=>"register",'plugin'=>"users")
		);
		$reviewIndex = new GigaAction(
			"reviewIndex",
			__("Review Index"),
			array("controller"=>"reviews","action"=>"index")
		);
		$addListing = new GigaAction(
			"listingAdd",
			__("Listing Add"),
			array("controller"=>"listings","action"=>"add")
		);
		$addReview = new GigaAction(
			"reviewAdd",
			__("Review Add"),
			array("controller"=>"reviews","action"=>"add")
		);
		$viewReview = new GigaAction(
			"reviewView",
			__("Review View"),
			array("controller"=>"reviews","action"=>"view")
		);
		$textSearch = new GigaAction(
				"text_search",
			__("Listing text search"),
			array("controller"=>"listings","action"=>"index","search")
		);
		$staticPages = new GigaAction(
			'staticpages', 
			__('Static Pages'), 
			array(
				'controller' => 'pages', 
				'action' => 'display',
				'params' => array(
					'pass' => array('pageName'),
					'named' => array('pageName' => '[[pageName]]')
				)
			)
		);
	require_once(APP.'plugins'.DS.'static_pages'.DS.'vendors'.DS.'giga_pages.php');
	$staticPagesList = GigaPages::getPages();
	$staticPagesList = Set::combine($staticPagesList,"{n}.page","{n}.title");
	$staticPages->setCombinations('pageName', $staticPagesList);
	$staticPages->setLabel('pageName', __('Selected page'));	
	$pages = cri("DynamicPage")->getAsGigaActionPages();
	
	$pages = am($pages,array($listingIndexPages,$advancesSearchPages,$registerPage,$reviewIndex,$addListing,$addReview,$viewReview,$textSearch,$staticPages));
	$SiteMapModel->pages = am($SiteMapModel->pages,$pages);
}

function AppShellTasksHook($shell)
{
	App::import('Vendor','SiteUrl');
	App::import("Vendor","SiteTreeCallbacks");
	App::import("Vendor","AppUtility");
	$shell->tasks[] = "DynamicFieldCache";
}
/**
 * 
 * @param FacebookUser $FacebookUserModel
 * @param array $fbInfo - Information fetched from facebook.
 */
function AppSetFacebookUserRegisterDataHook(FacebookUser $FacebookUserModel,$fbInfo)
{
	//you can chnage $FacebookUserModel->fbData as per requirement
	//prd($FacebookUserModel->fbData);
}
/**
 * 
 */
function AppOnFaceBookRegisterHook(FacebookUsersController $FacebookUserController,$fbInfo,$UserModel)
{
	$email = $fbInfo['email'];
	if($UserModel->hasAny(array("email"=>$email)))
	{
		$FacebookUserController->errorMsg(__("You facebook email is already present in our database."));
		$FacebookUserController->redirect('/');
	}
}
?>